package org.jfk.core.model;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;

/**
 * 简易sqlFilter。
 * 为保持简单化，建议放在where 1=1之后，一般情况下filter的第一个relation为and。
 * 过于复杂的逻辑单独处理，不建议用此类。
 * @author jxf
 * 2014年12月21日
 */
public class SqlFilter {
	public String sqlText;
	public List<Object> params;
	
	public SqlFilter(){
		sqlText = "";
		params = new ArrayList();
	}
	
	private void _add(String field,String op,String param){
		
		if ("like".equals(op)){
			sqlText = sqlText + field + " like ? ";
			params.add("%" + param + "%");
		}else if ("eq".equals(op)){
			sqlText = sqlText + field + " = ? ";
			params.add(param);
		}else if ("between".equals(op) && param.indexOf("-")>0){
			String v[] = param.split("-");
			sqlText = sqlText + field + " between ? and ? ";
			params.add(v[0].trim());
			params.add(v[1].trim());
		}
		
	}
	
	public void add(String relation,String field,String op,String param){
		if (relation == null){
			relation ="";
		}
		if (sqlText.length() == 0){
			//sqlText = " " +relation + " ( " + field +" "+ op + "?";
			sqlText = " " +relation + " ( ";
			//sqlText = " ( ";
			_add(field,op,param);
		}else{
			sqlText = sqlText + " " +relation + " ";
			_add(field,op,param);
		}
		
	}
	
	public void add(SqlFilter filter){

		if (StrKit.notBlank(sqlText)){
			sqlText = sqlText + filter.sqlText;
		}else{
			sqlText = filter.sqlText;
		}
		params.addAll(filter.params);
	}
	
	public String toString(){
		String s = "sql = {" + sqlText+"}; ";
		s=s+"params = "+ params.toString();
		return s;
	}
	
	public void end(){
		sqlText = sqlText+" )";
	}
	
	public static void main(String[] args){
		SqlFilter filter1 = new SqlFilter();
		filter1.add("and", "name", "like", "jxf");
		filter1.add("and", "id", "eq", "1");
		filter1.end();

		SqlFilter filter2 = new SqlFilter();
		filter2.add("and", "key1", "eq", "nb");
		filter2.add("or", "key2", "between", "nb1-nb2");
		filter2.end();
		
		filter1.add(filter2);
		
		System.out.println(filter1);
		
	}
}
